package cn.mcch.investigator.service;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import cn.mcch.investigator.application.InvestigatorApplication;
import cn.mcch.investigator.model.bean.ConfChild;
import cn.mcch.investigator.utils.L;
import cn.mcch.investigator.utils.ToastUtils;

public class SmsObserver extends ContentObserver {

    private ContentResolver mResolver;
    private Handler smsHandler;

    public SmsObserver(Handler handler, ContentResolver mResolver) {
        super(handler);
        this.mResolver = mResolver;
        this.smsHandler = handler;
    }

    @Override
    public void onChange(boolean selfChange) {
        L.e("监听到短信变化");
        Cursor mCursor = mResolver.query(Uri.parse("content://sms/inbox"),
                new String[]{"_id", "address", "body"}, null, null, "_id desc limit 1");
        if (mCursor == null) {
            return;
        }

        if (mCursor.getCount() <= 0) {
            return;
        }
        if (!mCursor.moveToFirst()) {
            return;
        }

        SmsInfo _smsInfo = new SmsInfo();

        int _inIndex = mCursor.getColumnIndex("_id");
        if (_inIndex != -1) {
            _smsInfo._id = mCursor.getString(_inIndex);
        }


        int addressIndex = mCursor.getColumnIndex("address");
        if (addressIndex != -1) {
            _smsInfo.smsAddress = mCursor.getString(addressIndex);
        }

        int bodyIndex = mCursor.getColumnIndex("body");
        if (bodyIndex != -1) {
            _smsInfo.smsBody = mCursor.getString(bodyIndex);
        }

        boolean isFind = true;
        for (ConfChild sms_no : InvestigatorApplication.getInstance().getSmsNo()) {
            if (_smsInfo.smsAddress.contains(sms_no.name)) {
                isFind = true;
                break;
            }
        }

        if (!isFind) return;

        Message msg = smsHandler.obtainMessage();
        msg.obj = _smsInfo;
        smsHandler.sendMessage(msg);

        if (mCursor != null) {
            mCursor.close();
            mCursor = null;
        }
    }
}